<template>
    <div v-loading="loading">
      <el-tabs v-model="activeName" class="demo-tabs" @tab-click="handleClick">
          <el-tab-pane label="任务信息" name="taskContent"></el-tab-pane>
          <el-tab-pane v-if="type!='sub'&&isAuth('view_zwglSubTaskInfo_subPage')" label="审批列表" name="subTaskCiontent"></el-tab-pane>
          <el-tab-pane label="消息留言" name="message"></el-tab-pane>
      </el-tabs>
      <!-- 任务内容 -->
      <!-- type=='sub'||publishStatus!='UNPUBLISHED'||nowRowData.taskStatus=='PENDING_APPROVAL' -->
      <div v-if="activeName=='taskContent'" class="btn tr w-100">
          <el-button type="primary" @click="exportTable">导出</el-button>
        </div>
      <TaskInfo v-if="activeName=='taskContent'" :is-read="type=='sub'||nowRowData.taskStatus=='ENDED'" :nowRowData="nowRowData"></TaskInfo>
      <div v-if="activeName=='taskContent'&&type!='sub'" class="publish_btn">
        <el-button v-if="nowRowData.taskStatus!='ENDED'" style="margin-left:20px" type="primary" @click="toSubmit">提交数据</el-button>
        <el-button v-if="publishStatus=='UNPUBLISHED'&&nowRowData.taskStatus!='ENDED'&&nowRowData.taskStatus!='PENDING_APPROVAL'" v-auth="'view_zwglSubTaskInfo_subPage'" type="primary" @click="creatSubTask">创建子任务</el-button>
      </div>
      <!-- 子任务信息 -->
      
      <SubTaskInfo v-if="activeName=='subTaskCiontent'" ref="subTaskInfo" :nowRowData="nowRowData" :dataId="nowRowData.id" @refresh="toRefresh"></SubTaskInfo>
      <!-- 归档记录 -->
  
      <!-- 消息通知 -->
      <div style="min-height: 500px" v-if="activeName=='message'">
        <Comments :nowRowData="nowRowData"></Comments>
      </div>
      
      <!-- 选择下发人的弹窗 -->
      <AplidDialog ref="aplidDialog" v-model="showSelect" titl="任务下发" width="80%">
        <div class="tip_part">
          说明：创建下发任务后，任务表格的内容，将会按照子任务提交数据自动计算。
        </div>
        <el-form>
          <el-form-item label="下发人：">
            <el-button @click="drawer=true" type="primary">选择下发人</el-button>
            <div style="width: 100%; margin-top: 20px">
              <el-tag style="margin-right: 10px; margin-bottom: 10px" v-for="tag in filterData" :key="tag.value" :type="tag.type">
                {{ tag.label }}
              </el-tag>
            </div>
          </el-form-item>
        </el-form>
        <div class="btn_part">
          <el-button @click="showSelect=false">取消</el-button>
          <el-button type="primary" @click="toPublish">确认</el-button>
        </div>
        <!-- 选择下级接收人 -->
      <el-drawer v-model="drawer" title="选接收人" direction="rtl" size="60%">
              <SelectRecipients @getFilterData="getFilterData"></SelectRecipients>
        <div style="width: 100%;display: flex;flex-direction: row-reverse">
          <el-button type="primary" @click="drawerClosed">保存</el-button>
        </div>
          </el-drawer>
      </AplidDialog>
      
    </div>
  </template>
  
  <script setup lang="ts">
  import { ref, reactive, toRefs, onMounted} from 'vue'
  // import PreviewTable from '@/views/governmentAffairs/overallTask/previewTable/index.vue'
  import SubTaskInfo from '@/views/governmentAffairs/overallTask/detailPart/subTaskInfo/index.vue'
  import SelectRecipients from '@/views/governmentAffairs/overallTask/addPart/selectRecipients/index.vue'
  import TaskInfo from '@/views/governmentAffairs/overallTask/detailPart/bottomTabs/taskInfo.vue'
  import Comments from '@/views/governmentAffairs/subTask/detailPart/comments/index.vue'
  import apiMod from '@/apiMod/index'
  import {isAuth} from '@/utils/util'
  
  import { getStore } from '@/utils/store'
  import FileSaver from 'file-saver'
  import useMqtt from '@/hooks/useMqttHooks'
  import { onDownloadFile, DowloadPreviewImage } from '@/utils/util'
  const { startMqtt,doUnSubscribe } = useMqtt()
  
  
  let props = defineProps({
    nowRowData:{
      type:Object,
      default:()=>({})
    },
    type:{
      type:String,
      default:'self'
    }
  })
  let showSelect = ref(false)
  let publishStatus = ref('UNPUBLISHED')
  publishStatus.value = props.nowRowData.publishStatus
  // metadata.value = props.nowRowData.metadataJson
  let type = inject("subDetailType")
  // 如果是type==sub
  // const getTableData = (id)=>{
  // 	apiMod.view_zwglTaskInfo_view(id).then(res=>{
  // 		console.log('hueo',res)
  //     metadata.value = res.data.metadataJson
  // 	})
  // }
  // if(type=='sub'){
  //   console.log('666',props.nowRowData)
  // 	getTableData(props.nowRowData.primaryKey)
  // }
  let drawer = ref(false)
  let emits = defineEmits(['currentTab','refresh'])
  
  // let tableData = ref({head:{},data:[]})
  
  let activeName = ref("taskContent")
  const handleClick = (a) => {
    emits('currentTab',a.paneName)
  }
  // let taskStatus = ref(props.nowRowData.taskStatus)
  // 提交掉填报内容
  const toSubmit = () =>{
    let fn = () =>{
      let params = {
          id:props.nowRowData.id,
          metadataJson:JSON.stringify(props.nowRowData.metadataJson)
        }
        apiMod.view_zwglTaskInfo_submit(params).then(res=>{
          if(res.code==0){
            emits('refresh')
            ElMessage({
              type: 'success',
              message: '操作成功',
            })
          }
        })
    }
    if(publishStatus.value=='UNPUBLISHED'&&props.nowRowData.taskStatus!='PENDING_APPROVAL'){
      ElMessageBox.confirm(
      '您未下发子任务，请问您是否要手动输入；本次提交审核成功后，将不会允许下发子任务，请慎重选择。',
      '提交',
      {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning',
      }
    )
      .then(() => {
        console.log('进入')
        fn()
      })
      .catch(() => {
        
      })
      return
    }
    fn()
  }
  // 创建任务处理
  let loading = ref(false)
  // let subTaskInfo = ref()
  let areaInfo = {
    dimension:"",
    list:[],
    type:""
  }
  let metadataJson = {
    head:{},
    data:[]
  }
  let dimension = ""
  let filterType = ""
  const creatHandle = () =>{
    loading.value = true
    // 提交
    let params = {
      ...props.nowRowData,
      dimension:dimension,
      metadataJson:JSON.stringify(metadataJson),
      "publishStatus": "PUBLISHED",
      "publishStatusLabel": "已发布",
      "tableTemplateId": "",
      "taskStatus": "TO_BE_SUBMITTED",
      "taskStatusLabel": "待提交",
    }
    apiMod.view_zwglTaskInfo_add(params).then(res=>{
      ElMessage.success('提交成功')
      // subTaskInfo.value.getTreeData()
      loading.value = false
      publishStatus.value = "PUBLISHED"
      showSelect.value = false
      emits("refresh")
     
    }).catch(err=>{
      loading.value = false
    })
  }
  
  // 创建子任务
  const creatSubTask = () =>{
    showSelect.value = true
  }
  
  const drawerClosed = () =>{
    handleTable()
    drawer.value = false
  }
  
  let filterData = ref([])
  const handleTable = () =>{
    // 处理一下表格
    dimension = areaInfo.dimension
      filterData.value = areaInfo.list
      if (filterData.value && filterData.value.length > 0) {
          metadataJson.head['th1'] = '接收人'
      } else if (filterData.value.length == 0) {
          metadataJson.head = {}
      }
      filterType = areaInfo.type
      //   nameList.value = []
      metadataJson.data = []
      filterData.value.forEach((el, index) => {
          metadataJson.data.push({ tr1: el.label, id: el.value })
      })
    
    // 和原有的表格组成一个新的
    let oldMetadataJson = props.nowRowData.metadataJson
    let keys = Object.keys(oldMetadataJson.head)
    let head = {...oldMetadataJson.head,...metadataJson.head}
   
    // 处理掉完成度和目标值
    keys.forEach((el,index)=>{
      if(!el.includes('_1')&&!el.includes('_2')){
        head[el]
        if(index>0){
            for (let i in metadataJson.data) {
            metadataJson.data[i]['tr' + (index+1)] = ''
        }
        }
      }else{
        delete head[el]
      }
    })
    metadataJson.head = head
    console.log('12得到选择的节点',metadataJson)
  }
  // 去下发
  const toPublish = () => {
    if(metadataJson.data.length==0){
      ElMessage.warning('请选择下发接收人')
    }else{
      creatHandle()
    }
  }
  const getFilterData = (data) =>{
    areaInfo = data
  }
  // 导出表格
  const exportTable = () =>{
    apiMod.view_zwglTaskInfo_export({id:props.nowRowData.id}).then(res=>{
      if(res.code==0){
        ElMessage.success({
        message: '导出成功',
        type: 'success',
      })
      }
    })
  }
 
  
  const toRefresh = () =>{
    emits('refresh')
  }
  
  </script>
  <style scoped lang="scss">
  .publish_btn{
    margin-top:20px;
    width: 100%;
    display: flex;
    flex-direction: row-reverse;
    justify-content: center;
    align-items: center;
  }
  .tip_part{
    height: 50px;
    width: 100%;
    background-color: rgba(0,0,0,0.3);
    margin-bottom: 10px;
    border-radius: 10px;
    padding: 10px;
    box-sizing: border-box;
  }
  .btn_part{
    width: 100%;
    display: flex;
    flex-direction: row;
    justify-content: center;
    align-items: center;
  }
  </style>